$(document).ready(function () {
	var sipStack = null;
	var session = null;
	var sessionCall = null;
	
	var contentType = 'application/pidf+xml';
	var publicId = null;
	
	var server = '10.69.173.68';
	
	var eventsListener = function (e) {
		//$('#eventsSIPStack').append(e.type + ' ');
		switch (e.type) {
			case 'started' : {
				login();
				//publishPresence();
				//subscribePresence();
				break;
			}
			case 'connected' : {
				if (e.session == session) {
					$('#result').text('Registered');
					$('#result').show();
					$('#callBtn').removeAttr('disabled');
					$('#videoCallBtn').removeAttr('disabled');
					$('#logoutBtn').removeAttr('disabled');
					$('#loginBtn').attr('disabled', 'disabled');
					break;
				}
			}
			case 'stopped' : {
				$('#result').text('Disconnected');
				$('#logoutBtn').attr('disabled', 'disabled');
				$('#loginBtn').removeAttr('disabled');
				$('#callBtn').attr('disabled', 'disabled');
				$('#videoCallBtn').attr('disabled', 'disabled');
				session = null;
				break;
			}
			case 'm_permission_accepted' : {
				$('#hangupBtn').removeAttr('disabled');
				$('#callBtn').attr('disabled', 'disabled');
				$('#videoCallBtn').attr('disabled', 'disabled');
				break;
			}
			case 'm_permission_refused' : {
				$('#callStatus').text('Media access forbidden');
				break;
			}
			case 'i_new_call' : {
				$('#callStatus').text(e.newSession.getRemoteFriendlyName() + ' is calling');
				$('#callStatus').slideDown(500);
				if (!sessionCall) {
					sessionCall = e.newSession;
					$('#answerBtn').removeAttr('disabled');
					$('#callBtn').attr('disabled', 'disabled');
					$('#videoCallBtn').attr('disabled', 'disabled');
				} else {
					e.newSession.reject();
				}
				break;
			}
		}
	};
	
	var eventsSessionListener = function (e) {
		$('#callStatus').text(e.description);
		$('#eventsAudioSession').text(e.type);
		switch (e.type) {
			/*case 'i_ao_request' : {
				$('#callStatus').text('Ringing ...');
				$('#ringBackTone').get(0).play();
				break;
			}*/
			/*case 'm_stream_audio_remote_added' : {
				$('#ringBackTone').get(0).pause();
			}*/
			case 'terminating' : case 'terminated' : {
				$('#callStatus').slideUp(500);
				$('#callBtn').removeAttr('disabled');
				$('#videoCallBtn').removeAttr('disabled');
				$('#hangupBtn').attr('disabled', 'disabled');
				$('#answerBtn').attr('disabled', 'disabled');
				$('#localVideo').removeAttr('src');
				$('#remoteVideo').removeAttr('src');
				sessionCall = null;
				break;
			}
		}
	};
	
	var eventsPresenceListener = function (e) {
		switch (e.type) {
			case 'i_notify' : {
				alert(e.getContentString());
				break;
			}
			/*case 'connecting' : case 'connected' : {
				alert('Request accepted');
				break;
			}*/
		}
	};
	
	var configCall = {
		audio_remote : document.getElementById('remoteAudio'),
		video_remote : document.getElementById('remoteVideo'),
		video_local : document.getElementById('localVideo'),
		events_listener : { events : '*', listener : eventsSessionListener },
		sip_caps: [
			{ name: '+g.oma.sip-im' },
			{ name: '+sip.ice' },
			{ name: 'language', value: '\"en,fr\"' }
		]
	};
	
	$('#loginBtn').click(function () {
		publicId = 'sip:' + $('#identity').val() + '@' + $('#domain').val();
		sipStack = new SIPml.Stack({
			realm : $('#domain').val(), // mandatory: domain name
			impi : $('#identity').val(), // mandatory: authorization name (IMS Private Identity)
			impu : publicId, // mandatory: valid SIP Uri (IMS Public Identity)
			password : $('#password').val(),
			display_name : $('#displayName').val(),
			websocket_proxy_url : 'ws://' + server + ':10060',
			outbound_proxy_url : 'udp://' + server + ':5060',
			ice_servers : [],
			enable_rtcweb_breaker : true,
			events_listener : { events : '*', listener : eventsListener }
		});
		sipStack.start();
	});
	
	$('#logoutBtn').click(function () {
		if (sipStack) {
			sipStack.stop();
			sipStack = null;
			$('#loginBtn').removeAttr('disabled');
		}
	});
	
	$('#callBtn').click(function () {
		if (!sessionCall) {
			$('#callStatus').slideDown(500);
			var number = 'sip:' + $('#number').val() + '@' + $('#domain').val();
			sessionCall = sipStack.newSession('call-audio', configCall);
			sessionCall.call(number, configCall);
		}
	});
	
	$('#videoCallBtn').click(function () {
		if (!sessionCall) {
			$('#callStatus').slideDown(500);
			var number = 'sip:' + $('#number').val() + '@' + $('#domain').val();
			sessionCall = sipStack.newSession('call-audiovideo', configCall);
			sessionCall.call(number, configCall);
		}
	});
	
	$('#hangupBtn').click(function () {
		if (sessionCall) {
			sessionCall.hangup({
				events_listener : { events : '*', listener : eventsSessionListener }
			});
			$('#ringBackTone').get(0).pause();
		}
	});
	
	$('#answerBtn').click(function () {
		if (sessionCall) {
			sessionCall.accept(configCall);
			$('#answerBtn').attr('disabled', 'disabled');
		}
	});
	
	function login() {
		session = sipStack.newSession('register', {
			expires : 300,
			events_listener : {events : '*', listener : eventsListener}
		});
		session.register();
	};
	
	function publishPresence() {
		if (sipStack) {
			var xhr = new XMLHttpRequest();
			var publishSession = sipStack.newSession('publish', {
				expires : 200
			});
			
			xhr.onload = function () {
				var doc = xhr.responseXML;
				var presenceNode = doc.documentElement;
				presenceNode.setAttribute('entity', publicId);
				presenceNode.getElementsByTagName('basic')[0].textContent = 'open';
				presenceNode.getElementsByTagName('note')[0].textContent = $('#message').val();
				var serializer = new XMLSerializer();
				var content = serializer.serializeToString(doc);
				publishSession.publish(content, contentType, {
					expires : 200
				});
				//alert(content);
			};
			
			xhr.open("GET", "presence.xml");
			xhr.responseType = "document";
			xhr.send();
		}
	};
	
	function subscribePresence() {
		if (sipStack) {
			var subscribeSession = sipStack.newSession('subscribe', {
				expires : 200,
				events_listener : {events : '*', listener : eventsPresenceListener}
			});
			/*$('li.contact').each(function (index, element) {
				var uri = 'sip:' + element.id + '@' + server;
				subscribeSession.subscribe(element.id);
			});*/
			//var k = subscribeSession.subscribe('sip:1063@10.69.173.68');
			subscribeSession.subscribe('1063');
			//alert(k);
		}
	};
	
	$('#subscribeBtn').click(subscribePresence);
});
